<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <title>redis的介绍与使用 - L_B__</title><meta name="referrer" content="no-referrer">
<meta name="description" content="redis的介绍与使用"><meta property="og:title" content="redis的介绍与使用" />
<meta property="og:description" content="redis的介绍与使用" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://acking-you.github.io/posts/redis%E7%9A%84%E4%BB%8B%E7%BB%8D%E4%B8%8E%E4%BD%BF%E7%94%A8/" /><meta property="og:image" content="https://acking-you.github.io/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2022-06-11T00:00:00+00:00" />
<meta property="article:modified_time" content="2022-06-11T00:00:00+00:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://acking-you.github.io/logo.png"/>

<meta name="twitter:title" content="redis的介绍与使用"/>
<meta name="twitter:description" content="redis的介绍与使用"/>
<meta name="application-name" content="FeelIt">
<meta name="apple-mobile-web-app-title" content="FeelIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="canonical" href="https://acking-you.github.io/posts/redis%E7%9A%84%E4%BB%8B%E7%BB%8D%E4%B8%8E%E4%BD%BF%E7%94%A8/" /><link rel="prev" href="https://acking-you.github.io/posts/java%E8%AF%BE%E8%AE%BEswing%E7%94%A8%E5%88%86%E5%B1%82%E6%80%9D%E6%83%B3%E6%B5%85%E5%86%99%E4%B8%AA%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F%E8%AF%BE%E8%AE%BE/" /><link rel="next" href="https://acking-you.github.io/posts/%E9%9D%A2%E8%AF%95%E5%85%AB%E8%82%A1%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C1/" /><link rel="stylesheet" href="/css/page.min.css"><link rel="stylesheet" href="/css/home.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "redis的介绍与使用",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/acking-you.github.io\/posts\/redis%E7%9A%84%E4%BB%8B%E7%BB%8D%E4%B8%8E%E4%BD%BF%E7%94%A8\/"
        },"genre": "posts","keywords": "redis的介绍与使用","wordcount":  10174 ,
        "url": "https:\/\/acking-you.github.io\/posts\/redis%E7%9A%84%E4%BB%8B%E7%BB%8D%E4%B8%8E%E4%BD%BF%E7%94%A8\/","datePublished": "2022-06-11T00:00:00+00:00","dateModified": "2022-06-11T00:00:00+00:00","publisher": {
            "@type": "Organization",
            "name": "作者"},"author": {
                "@type": "Person",
                "name": "作者"
            },"description": "redis的介绍与使用"
    }
    </script></head><body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="L_B__">L_B__</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-desktop">
                        <a href="#" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="L_B__">L_B__</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-mobile">
                        <a href="#" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="#" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><div class="menu-item"><a href="javascript:void(0);" class="theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div></div>
    </div>
</header><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single" data-toc="disable"><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/img_convert/e706274b97f65b3aac9471d1da024918.png#pic_center"
        data-srcset="https://img-blog.csdnimg.cn/img_convert/e706274b97f65b3aac9471d1da024918.png#pic_center, https://img-blog.csdnimg.cn/img_convert/e706274b97f65b3aac9471d1da024918.png#pic_center 1.5x, https://img-blog.csdnimg.cn/img_convert/e706274b97f65b3aac9471d1da024918.png#pic_center 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/img_convert/e706274b97f65b3aac9471d1da024918.png#pic_center"
        title="redis的介绍与使用" /></div><div class="single-card" data-image="true"><h2 class="single-title animated flipInX">redis的介绍与使用</h2><div class="post-meta">
                <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>作者</a></span>&nbsp;<span class="post-category">出版于  <a href="/categories/javaweb%E7%AC%94%E8%AE%B0/"><i class="far fa-folder fa-fw"></i>JavaWeb笔记</a></span></div>
                <div class="post-meta-line"><span><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2022-06-11">2022-06-11</time></span>&nbsp;<span><i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 10174 字</span>&nbsp;
                    <span><i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 21 分钟</span>&nbsp;</div>
            </div>
            
            <hr><div class="details toc" id="toc-static"  data-kept="">
                    <div class="details-summary toc-title">
                        <span>目录</span>
                        <span><i class="details-icon fas fa-angle-right"></i></span>
                    </div>
                    <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#nosql概论">NoSQL概论</a></li>
    <li><a href="#redis安装和部署">Redis安装和部署</a></li>
    <li><a href="#基本操作">基本操作</a>
      <ul>
        <li><a href="#数据操作">数据操作</a></li>
      </ul>
    </li>
    <li><a href="#数据类型介绍">数据类型介绍</a>
      <ul>
        <li><a href="#hash">Hash</a></li>
        <li><a href="#list">List</a></li>
        <li><a href="#set和sortedset">Set和SortedSet</a></li>
      </ul>
    </li>
    <li><a href="#持久化">持久化</a>
      <ul>
        <li><a href="#rdb">RDB</a></li>
        <li><a href="#aof">AOF</a></li>
      </ul>
    </li>
    <li><a href="#事务和锁机制">事务和锁机制</a>
      <ul>
        <li><a href="#锁">锁</a></li>
      </ul>
    </li>
    <li><a href="#使用java与redis交互">使用Java与Redis交互</a>
      <ul>
        <li><a href="#基本操作-1">基本操作</a></li>
        <li><a href="#springboot整合redis">SpringBoot整合Redis</a></li>
      </ul>
    </li>
    <li><a href="#使用redis做缓存">使用Redis做缓存</a>
      <ul>
        <li><a href="#mybatis二级缓存">Mybatis二级缓存</a></li>
        <li><a href="#token持久化存储">Token持久化存储</a></li>
      </ul>
    </li>
    <li><a href="#三大缓存问题">三大缓存问题</a>
      <ul>
        <li><a href="#缓存穿透">缓存穿透</a></li>
        <li><a href="#缓存击穿">缓存击穿</a></li>
        <li><a href="#缓存雪崩">缓存雪崩</a></li>
      </ul>
    </li>
  </ul>
</nav></div>
                </div><div class="content" id="content"><p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic4.zhimg.com%2Fv2-054d8ff6135b3638aca543eff7424f98_1200x500.jpg&amp;refer=http%3A%2F%2Fpic4.zhimg.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644500043&amp;t=72a4f8ecfca9ff5a2a0b3896edef4be7"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic4.zhimg.com%2Fv2-054d8ff6135b3638aca543eff7424f98_1200x500.jpg&amp;refer=http%3A%2F%2Fpic4.zhimg.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644500043&amp;t=72a4f8ecfca9ff5a2a0b3896edef4be7, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic4.zhimg.com%2Fv2-054d8ff6135b3638aca543eff7424f98_1200x500.jpg&amp;refer=http%3A%2F%2Fpic4.zhimg.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644500043&amp;t=72a4f8ecfca9ff5a2a0b3896edef4be7 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic4.zhimg.com%2Fv2-054d8ff6135b3638aca543eff7424f98_1200x500.jpg&amp;refer=http%3A%2F%2Fpic4.zhimg.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644500043&amp;t=72a4f8ecfca9ff5a2a0b3896edef4be7 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic4.zhimg.com%2Fv2-054d8ff6135b3638aca543eff7424f98_1200x500.jpg&amp;refer=http%3A%2F%2Fpic4.zhimg.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644500043&amp;t=72a4f8ecfca9ff5a2a0b3896edef4be7"
        title="点击查看源网页" /></p>
<p><a href="https://www.bilibili.com/video/BV1UL411V7f3?p=28&amp;share_source=copy_pc" target="_blank" rel="noopener noreffer">视频讲解链接</a></p>
<h1 id="redis数据库">Redis数据库</h1>
<p><strong>灵魂拷问</strong>：不是学了MySQL吗，存数据也能存了啊，又学一个数据库干嘛？</p>
<p>在前面我们学习了MySQL数据库，它是一种传统的关系型数据库，我们可以使用MySQL来更好地管理和组织我们的数据，虽然在小型Web应用下，只需要一个MySQL+Mybatis自带的缓存系统就可以胜任大部分的数据存储工作。但是MySQL的缺点也很明显，它的数据始终是存储在硬盘上的，对于我们的用户信息这种不需要经常发生修改的内容，使用MySQL存储确实可以，但是如果是快速更新或是频繁使用的数据，比如微博热搜、双十一秒杀，这些数据不仅要求服务器需要提供更高的响应速度，而且还需要面对短时间内上百万甚至上千万次访问，而MySQL的磁盘IO读写性能完全不能满足上面的需求，能够满足上述需求的只有内存，因为速度远高于磁盘IO。</p>
<p>因此，我们需要寻找一种更好的解决方案，来存储上述这类特殊数据，弥补MySQL的不足，以应对大数据时代的重重考验。</p>
<h2 id="nosql概论">NoSQL概论</h2>
<p>NoSQL全称是Not Only SQL（不仅仅是SQL）它是一种非关系型数据库，相比传统SQL关系型数据库，它：</p>
<ul>
<li>不保证关系数据的ACID特性</li>
<li>并不遵循SQL标准</li>
<li>消除数据之间关联性</li>
</ul>
<p>乍一看，这玩意不比MySQL垃圾？我们再来看看它的优势：</p>
<ul>
<li>远超传统关系型数据库的性能</li>
<li>非常易于扩展</li>
<li>数据模型更加灵活</li>
<li>高可用</li>
</ul>
<p>这样，NoSQL的优势一下就出来了，这不就是我们正要寻找的高并发海量数据的解决方案吗！</p>
<p>NoSQL数据库分为以下几种：</p>
<ul>
<li>**键值存储数据库：**所有的数据都是以键值方式存储的，类似于我们之前学过的HashMap，使用起来非常简单方便，性能也非常高。</li>
<li>**列存储数据库：**这部分数据库通常是用来应对分布式存储的海量数据。键仍然存在，但是它们的特点是指向了多个列。</li>
<li>**文档型数据库：**它是以一种特定的文档格式存储数据，比如JSON格式，在处理网页等复杂数据时，文档型数据库比传统键值数据库的查询效率更高。</li>
<li>**图形数据库：**利用类似于图的数据结构存储数据，结合图相关算法实现高速访问。</li>
</ul>
<p>其中我们要学习的Redis数据库，就是一个开源的<strong>键值存储数据库</strong>，所有的数据全部存放在内存中，它的性能大大高于磁盘IO，并且它也可以支持数据持久化，他还支持横向扩展、主从复制等。</p>
<p>实际生产中，我们一般会配合使用Redis和MySQL以发挥它们各自的优势，取长补短。</p>
<h2 id="redis安装和部署">Redis安装和部署</h2>
<p>我们这里还是使用Windows安装Redis服务器，但是官方指定是安装到Linux服务器上，我们后面学习了Linux之后，再来安装到Linux服务器上。由于官方并没有提供Windows版本的安装包，我们需要另外寻找：</p>
<ul>
<li>官网地址：https://redis.io</li>
<li>GitHub Windows版本维护地址：https://github.com/tporadowski/redis/releases</li>
</ul>
<hr>
<h2 id="基本操作">基本操作</h2>
<p>在我们之前使用MySQL时，我们需要先在数据库中创建一张表，并定义好表的每个字段内容，最后再通过<code>insert</code>语句向表中添加数据，而Redis并不具有MySQL那样的严格的表结构，Redis是一个键值数据库，因此，可以像Map一样的操作方式，通过键值对向Redis数据库中添加数据（操作起来类似于向一个HashMap中存放数据）</p>
<p>在Redis下，数据库是由一个整数索引标识，而不是由一个数据库名称。 默认情况下，我们连接Redis数据库之后，会使用0号数据库，我们可以通过Redis配置文件中的参数来修改数据库总数，默认为16个。</p>
<p>我们可以通过<code>select</code>语句进行切换：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="k">select</span><span class="w"> </span><span class="err">序号</span><span class="p">;</span><span class="w">
</span></code></pre></div><h3 id="数据操作">数据操作</h3>
<p>我们来看看，如何向Redis数据库中添加数据：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="k">set</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">value</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 一次性多个
</span><span class="c1"></span><span class="n">mset</span><span class="w"> </span><span class="p">[</span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">value</span><span class="o">&gt;</span><span class="p">]...</span><span class="w">
</span></code></pre></div><p>所有存入的数据默认会以<strong>字符串</strong>的形式保存，键值具有一定的命名规范，以方便我们可以快速定位我们的数据属于哪一个部分，比如用户的数据：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="c1">-- 使用冒号来进行板块分割，比如下面表示用户XXX的信息中的name属性，值为lbw
</span><span class="c1"></span><span class="k">set</span><span class="w"> </span><span class="k">user</span><span class="p">:</span><span class="n">info</span><span class="p">:</span><span class="err">用户</span><span class="n">ID</span><span class="p">:</span><span class="n">name</span><span class="w"> </span><span class="n">lbw</span><span class="w">
</span></code></pre></div><p>我们可以通过键值获取存入的值：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="k">get</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p>你以为Redis就仅仅只是存取个数据吗？它还支持数据的过期时间设定：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="k">set</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">value</span><span class="o">&gt;</span><span class="w"> </span><span class="n">EX</span><span class="w"> </span><span class="err">秒</span><span class="w">
</span><span class="w"></span><span class="k">set</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">value</span><span class="o">&gt;</span><span class="w"> </span><span class="n">PX</span><span class="w"> </span><span class="err">毫秒</span><span class="w">
</span></code></pre></div><p>当数据到达指定时间时，会被自动删除。我们也可以单独为其他的键值对设置过期时间：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">expire</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="err">秒</span><span class="w">
</span></code></pre></div><p>通过下面的命令来查询某个键值对的过期时间还剩多少：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">ttl</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 毫秒显示
</span><span class="c1"></span><span class="n">pttl</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 转换为永久
</span><span class="c1"></span><span class="n">persist</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p>那么当我们想直接删除这个数据时呢？直接使用：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">del</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="p">...</span><span class="w">
</span></code></pre></div><p>删除命令可以同时拼接多个键值一起删除。</p>
<p>当我们想要查看数据库中所有的键值时：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">keys</span><span class="w"> </span><span class="o">*</span><span class="w">
</span></code></pre></div><p>也可以查询某个键是否存在：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="k">exists</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="p">...</span><span class="w">
</span></code></pre></div><p>还可以随机拿一个键：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">randomkey</span><span class="w">
</span></code></pre></div><p>我们可以将一个数据库中的内容移动到另一个数据库中：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="k">move</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="err">数据库序号</span><span class="w">
</span></code></pre></div><p>修改一个键为另一个键：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="k">rename</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="err">新的名称</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 下面这个会检查新的名称是否已经存在
</span><span class="c1"></span><span class="n">renamex</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="err">新的名称</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p>如果存放的数据是一个数字，我们还可以对其进行自增自减操作：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="c1">-- 等价于a = a + 1
</span><span class="c1"></span><span class="n">incr</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 等价于a = a + b
</span><span class="c1"></span><span class="n">incrby</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="n">b</span><span class="w">
</span><span class="w"></span><span class="c1">-- 等价于a = a - 1
</span><span class="c1"></span><span class="n">decr</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p>最后就是查看值的数据类型：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="k">type</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p>Redis数据库也支持多种数据类型，但是它更偏向于我们在Java中认识的那些数据类型。</p>
<h2 id="数据类型介绍">数据类型介绍</h2>
<p>一个键值对除了存储一个String类型的值以外，还支持多种常用的数据类型。</p>
<h3 id="hash">Hash</h3>
<p>这种类型本质上就是一个HashMap，也就是嵌套了一个HashMap罢了，在Java中就像这样：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="err">#</span><span class="n">Redis默认存String类似于这样</span><span class="err">：</span>
<span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;</span> <span class="n">hash</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;&gt;();</span>
<span class="err">#</span><span class="n">Redis存Hash类型的数据类似于这样</span><span class="err">：</span>
<span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;&gt;</span> <span class="n">hash</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;&gt;();</span>
</code></pre></div><p>它比较适合存储类这样的数据，由于值本身又是一个Map，因此我们可以在此Map中放入类的各种属性和值，以实现一个Hash数据类型存储一个类的数据。</p>
<p>我们可以像这样来添加一个Hash类型的数据：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">hset</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="p">[</span><span class="o">&lt;</span><span class="err">字段</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="err">值</span><span class="o">&gt;</span><span class="p">]...</span><span class="w">
</span></code></pre></div><p>我们可以直接获取：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">hget</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="err">字段</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 如果想要一次性获取所有的字段和值
</span><span class="c1"></span><span class="n">hgetall</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p>同样的，我们也可以判断某个字段是否存在：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">hexists</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="err">字段</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p>删除Hash中的某个字段：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">hdel</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p>我们发现，在操作一个Hash时，实际上就是我们普通操作命令前面添加一个<code>h</code>，这样就能以同样的方式去操作Hash里面存放的键值对了，这里就不一一列出所有的操作了。我们来看看几个比较特殊的。</p>
<p>我们现在想要知道Hash中一共存了多少个键值对：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">hlen</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p>我们也可以一次性获取所有字段的值：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">hvals</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p>唯一需要注意的是，Hash中只能存放字符串值，不允许出现嵌套的的情况。</p>
<h3 id="list">List</h3>
<p>我们接着来看List类型，实际上这个猜都知道，它就是一个列表，而列表中存放一系列的字符串，它支持随机访问，支持双端操作，就像我们使用Java中的LinkedList一样。</p>
<p>我们可以直接向一个已存在或是不存在的List中添加数据，如果不存在，会自动创建：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="c1">-- 向列表头部添加元素
</span><span class="c1"></span><span class="n">lpush</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">element</span><span class="o">&gt;</span><span class="p">...</span><span class="w">
</span><span class="w"></span><span class="c1">-- 向列表尾部添加元素
</span><span class="c1"></span><span class="n">rpush</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">element</span><span class="o">&gt;</span><span class="p">...</span><span class="w">
</span><span class="w"></span><span class="c1">-- 在指定元素前面/后面插入元素
</span><span class="c1"></span><span class="n">linsert</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="k">before</span><span class="o">/</span><span class="k">after</span><span class="w"> </span><span class="o">&lt;</span><span class="err">指定元素</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">element</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p>同样的，获取元素也非常简单：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="c1">-- 根据下标获取元素
</span><span class="c1"></span><span class="n">lindex</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="err">下标</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 获取并移除头部元素
</span><span class="c1"></span><span class="n">lpop</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 获取并移除尾部元素
</span><span class="c1"></span><span class="n">rpop</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 获取指定范围内的
</span><span class="c1"></span><span class="n">lrange</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="k">start</span><span class="w"> </span><span class="n">stop</span><span class="w">
</span></code></pre></div><p>注意下标可以使用负数来表示从后到前数的数字（Python：搁这儿抄呢是吧）:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="c1">-- 获取列表a中的全部元素
</span><span class="c1"></span><span class="n">lrange</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="o">-</span><span class="mi">1</span><span class="w">
</span></code></pre></div><p>没想到吧，push和pop还能连着用呢：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="c1">-- 从前一个数组的最后取一个数出来放到另一个数组的头部，并返回元素
</span><span class="c1"></span><span class="n">rpoplpush</span><span class="w"> </span><span class="err">当前数组</span><span class="w"> </span><span class="err">目标数组</span><span class="w">
</span></code></pre></div><p>它还支持阻塞操作，类似于生产者和消费者，比如我们想要等待列表中有了数据后再进行pop操作：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="c1">-- 如果列表中没有元素，那么就等待，如果指定时间（秒）内被添加了数据，那么就执行pop操作，如果超时就作废，支持同时等待多个列表，只要其中一个列表有元素了，那么就能执行
</span><span class="c1"></span><span class="n">blpop</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="p">...</span><span class="w"> </span><span class="n">timeout</span><span class="w">
</span></code></pre></div><h3 id="set和sortedset">Set和SortedSet</h3>
<p>Set集合其实就像Java中的HashSet一样（我们在JavaSE中已经讲解过了，HashSet本质上就是利用了一个HashMap，但是Value都是固定对象，仅仅是Key不同）它不允许出现重复元素，不支持随机访问，但是能够利用Hash表提供极高的查找效率。</p>
<p>向Set中添加一个或多个值：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">sadd</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">value</span><span class="o">&gt;</span><span class="p">...</span><span class="w">
</span></code></pre></div><p>查看Set集合中有多少个值：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">scard</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p>判断集合中是否包含：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="c1">-- 是否包含指定值
</span><span class="c1"></span><span class="n">sismember</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">value</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 列出所有值
</span><span class="c1"></span><span class="n">smembers</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p>集合之间的运算：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="c1">-- 集合之间的差集
</span><span class="c1"></span><span class="n">sdiff</span><span class="w"> </span><span class="o">&lt;</span><span class="n">key1</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">key2</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 集合之间的交集
</span><span class="c1"></span><span class="n">sinter</span><span class="w"> </span><span class="o">&lt;</span><span class="n">key1</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">key2</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 求并集
</span><span class="c1"></span><span class="n">sunion</span><span class="w"> </span><span class="o">&lt;</span><span class="n">key1</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">key2</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 将集合之间的差集存到目标集合中
</span><span class="c1"></span><span class="n">sdiffstore</span><span class="w"> </span><span class="err">目标</span><span class="w"> </span><span class="o">&lt;</span><span class="n">key1</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">key2</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 同上
</span><span class="c1"></span><span class="n">sinterstore</span><span class="w"> </span><span class="err">目标</span><span class="w"> </span><span class="o">&lt;</span><span class="n">key1</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">key2</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 同上
</span><span class="c1"></span><span class="n">sunionstore</span><span class="w"> </span><span class="err">目标</span><span class="w"> </span><span class="o">&lt;</span><span class="n">key1</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">key2</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p>移动指定值到另一个集合中：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">smove</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="err">目标</span><span class="w"> </span><span class="n">value</span><span class="w"> 
</span></code></pre></div><p>移除操作：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="c1">-- 随机移除一个幸运儿
</span><span class="c1"></span><span class="n">spop</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 移除指定
</span><span class="c1"></span><span class="n">srem</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">value</span><span class="o">&gt;</span><span class="p">...</span><span class="w">
</span></code></pre></div><p>那么如果我们要求Set集合中的数据按照我们指定的顺序进行排列怎么办呢？这时就可以使用SortedSet，它支持我们为每个值设定一个分数，分数的大小决定了值的位置，所以它是有序的。</p>
<p>我们可以添加一个带分数的值：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">zadd</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="p">[</span><span class="o">&lt;</span><span class="n">value</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">score</span><span class="o">&gt;</span><span class="p">]...</span><span class="w">
</span></code></pre></div><p>同样的：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="c1">-- 查询有多少个值
</span><span class="c1"></span><span class="n">zcard</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">
</span><span class="w"></span><span class="c1">-- 移除
</span><span class="c1"></span><span class="n">zrem</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">value</span><span class="o">&gt;</span><span class="p">...</span><span class="w">
</span><span class="w"></span><span class="c1">-- 获取区间内的所有
</span><span class="c1"></span><span class="n">zrange</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="k">start</span><span class="w"> </span><span class="n">stop</span><span class="w">
</span></code></pre></div><p>由于所有的值都有一个分数，我们也可以根据分数段来获取：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="c1">-- 通过分数段查看
</span><span class="c1"></span><span class="n">zrangebyscore</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="k">start</span><span class="w"> </span><span class="n">stop</span><span class="w"> </span><span class="p">[</span><span class="n">withscores</span><span class="p">]</span><span class="w"> </span><span class="p">[</span><span class="k">limit</span><span class="p">]</span><span class="w">
</span><span class="w"></span><span class="c1">-- 统计分数段内的数量
</span><span class="c1"></span><span class="n">zcount</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w">  </span><span class="k">start</span><span class="w"> </span><span class="n">stop</span><span class="w">
</span><span class="w"></span><span class="c1">-- 根据分数获取指定值的排名
</span><span class="c1"></span><span class="n">zrank</span><span class="w"> </span><span class="o">&lt;</span><span class="k">key</span><span class="o">&gt;</span><span class="w"> </span><span class="o">&lt;</span><span class="n">value</span><span class="o">&gt;</span><span class="w">
</span></code></pre></div><p><a href="https://www.jianshu.com/p/32b9fe8c20e1" target="_blank" rel="noopener noreffer">https://www.jianshu.com/p/32b9fe8c20e1</a></p>
<p>有关Bitmap、HyperLogLog和Geospatial等数据类型，这里暂时不做介绍，感兴趣可以自行了解。</p>
<hr>
<h2 id="持久化">持久化</h2>
<p>我们知道，Redis数据库中的数据都是存放在内存中，虽然很高效，但是这样存在一个非常严重的问题，如果突然停电，那我们的数据不就全部丢失了吗？它不像硬盘上的数据，断电依然能够保存。</p>
<p>这个时候我们就需要持久化，我们需要将我们的数据备份到硬盘上，防止断电或是机器故障导致的数据丢失。</p>
<p>持久化的实现方式有两种方案：一种是直接保存当前<strong>已经存储的数据</strong>，相当于复制内存中的数据到硬盘上，需要恢复数据时直接读取即可；还有一种就是保存我们存放数据的<strong>所有过程</strong>，需要恢复数据时，只需要将整个过程完整地重演一遍就能保证与之前数据库中的内容一致。</p>
<h3 id="rdb">RDB</h3>
<p>RDB就是我们所说的第一种解决方案，那么如何将数据保存到本地呢？我们可以使用命令：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">save</span><span class="w">
</span><span class="w"></span><span class="c1">-- 注意上面这个命令是直接保存，会占用一定的时间，也可以单独开一个子进程后台执行保存
</span><span class="c1"></span><span class="n">bgsave</span><span class="w">
</span></code></pre></div><p>执行后，会在服务端目录下生成一个dump.rdb文件，而这个文件中就保存了内存中存放的数据，当服务器重启后，会自动加载里面的内容到对应数据库中。保存后我们可以关闭服务器：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">shutdown</span><span class="w">
</span></code></pre></div><p>重启后可以看到数据依然存在。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fqqe2.com%2Fjava%2Fzb_users%2Fupload%2F2020%2F04%2F202004281588086055367603.png&amp;refer=http%3A%2F%2Fqqe2.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644843952&amp;t=ec4cd6eb2c6d47a10aff5b9f264d2f16"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fqqe2.com%2Fjava%2Fzb_users%2Fupload%2F2020%2F04%2F202004281588086055367603.png&amp;refer=http%3A%2F%2Fqqe2.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644843952&amp;t=ec4cd6eb2c6d47a10aff5b9f264d2f16, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fqqe2.com%2Fjava%2Fzb_users%2Fupload%2F2020%2F04%2F202004281588086055367603.png&amp;refer=http%3A%2F%2Fqqe2.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644843952&amp;t=ec4cd6eb2c6d47a10aff5b9f264d2f16 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fqqe2.com%2Fjava%2Fzb_users%2Fupload%2F2020%2F04%2F202004281588086055367603.png&amp;refer=http%3A%2F%2Fqqe2.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644843952&amp;t=ec4cd6eb2c6d47a10aff5b9f264d2f16 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fqqe2.com%2Fjava%2Fzb_users%2Fupload%2F2020%2F04%2F202004281588086055367603.png&amp;refer=http%3A%2F%2Fqqe2.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644843952&amp;t=ec4cd6eb2c6d47a10aff5b9f264d2f16"
        title="点击查看图片来源" /></p>
<p>虽然这种方式非常方便，但是由于会完整复制所有的数据，如果数据库中的数据量比较大，那么复制一次可能就需要花费大量的时间，所以我们可以每隔一段时间自动进行保存；还有就是，如果我们基本上都是在进行读操作，而没有进行写操作，实际上只需要偶尔保存一次即可，因为数据几乎没有怎么变化，可能两次保存的都是一样的数据。</p>
<p>我们可以在配置文件中设置自动保存，并设定在一段时间内写入多少数据时，执行一次保存操作：</p>
<pre><code>save 300 10 # 300秒（5分钟）内有10个写入
save 60 10000 # 60秒（1分钟）内有10000个写入
</code></pre><p>配置的save使用的都是bgsave后台执行。</p>
<h3 id="aof">AOF</h3>
<p>虽然RDB能够很好地解决数据持久化问题，但是它的缺点也很明显：每次都需要去完整地保存整个数据库中的数据，同时后台保存过程中也会产生额外的内存开销，最严重的是它并不是实时保存的，如果在自动保存触发之前服务器崩溃，那么依然会导致少量数据的丢失。</p>
<p>而AOF就是另一种方式，它会以日志的形式将我们每次执行的命令都进行保存，服务器重启时会将所有命令依次执行，通过这种重演的方式将数据恢复，这样就能很好解决实时性存储问题。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://qqe2.com/java/zb_users/upload/2020/04/202004281588086068660716.png"
        data-srcset="https://qqe2.com/java/zb_users/upload/2020/04/202004281588086068660716.png, https://qqe2.com/java/zb_users/upload/2020/04/202004281588086068660716.png 1.5x, https://qqe2.com/java/zb_users/upload/2020/04/202004281588086068660716.png 2x"
        data-sizes="auto"
        alt="https://qqe2.com/java/zb_users/upload/2020/04/202004281588086068660716.png"
        title="rdb和aof区别" /></p>
<p>但是，我们多久写一次日志呢？我们可以自己配置保存策略，有三种策略：</p>
<ul>
<li>always：每次执行写操作都会保存一次</li>
<li>everysec：每秒保存一次（默认配置），这样就算丢失数据也只会丢一秒以内的数据</li>
<li>no：看系统心情保存</li>
</ul>
<p>可以在配置文件中配置：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="o">#</span><span class="w"> </span><span class="err">注意得改成也是</span><span class="w">
</span><span class="w"></span><span class="n">appendonly</span><span class="w"> </span><span class="n">yes</span><span class="w">
</span><span class="w">
</span><span class="w"></span><span class="o">#</span><span class="w"> </span><span class="n">appendfsync</span><span class="w"> </span><span class="n">always</span><span class="w">
</span><span class="w"></span><span class="n">appendfsync</span><span class="w"> </span><span class="n">everysec</span><span class="w">
</span><span class="w"></span><span class="o">#</span><span class="w"> </span><span class="n">appendfsync</span><span class="w"> </span><span class="k">no</span><span class="w">
</span></code></pre></div><p>重启服务器后，可以看到服务器目录下多了一个<code>appendonly.aof</code>文件，存储的就是我们执行的命令。</p>
<p>AOF的缺点也很明显，每次服务器启动都需要进行过程重演，相比RDB更加耗费时间，并且随着我们的操作变多，不断累计，可能到最后我们的aof文件会变得无比巨大，我们需要一个改进方案来优化这些问题。</p>
<p>Redis有一个AOF重写机制进行优化，比如我们执行了这样的语句：</p>
<pre><code>lpush test 666
lpush test 777
lpush test 888
</code></pre><p>实际上用一条语句也可以实现：</p>
<pre><code>lpush test 666 777 888
</code></pre><p>正是如此，只要我们能够保证最终的重演结果和原有语句的结果一致，无论语句如何修改都可以，所以我们可以通过这种方式将多条语句进行压缩。</p>
<p>我们可以输入命令来手动执行重写操作：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">bgrewriteaof</span><span class="w">
</span></code></pre></div><p>或是在配置文件中配置自动重写：</p>
<pre><code># 百分比计算，这里不多介绍
auto-aof-rewrite-percentage 100
# 当达到这个大小时，触发自动重写
auto-aof-rewrite-min-size 64mb
</code></pre><p>至此，我们就完成了两种持久化方案的介绍，最后我们再来进行一下总结：</p>
<ul>
<li>AOF：
<ul>
<li>优点：存储速度快、消耗资源少、支持实时存储</li>
<li>缺点：加载速度慢、数据体积大</li>
</ul>
</li>
<li>RDB：
<ul>
<li>优点：加载速度快、数据体积小</li>
<li>缺点：存储速度慢大量消耗资源、会发生数据丢失</li>
</ul>
</li>
</ul>
<hr>
<h2 id="事务和锁机制">事务和锁机制</h2>
<p>和MySQL一样，在Redis中也有事务机制，当我们需要保证多条命令一次性完整执行而中途不受到其他命令干扰时，就可以使用事务机制。</p>
<p>我们可以使用命令来直接开启事务：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">multi</span><span class="w">
</span></code></pre></div><p>当我们输入完所有要执行的命令时，可以使用命令来立即执行事务：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="k">exec</span><span class="w">
</span></code></pre></div><p>我们也可以中途取消事务：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">discard</span><span class="w">
</span></code></pre></div><p>实际上整个事务是创建了一个命令队列，它不像MySQL那种在事务中也能单独得到结果，而是我们提前将所有的命令装在队列中，但是并不会执行，而是等我们提交事务的时候再统一执行。</p>
<h3 id="锁">锁</h3>
<p>又提到锁了，实际上这个概念对我们来说已经不算是陌生了。实际上在Redis中也会出现多个命令同时竞争同一个数据的情况，比如现在有两条命令同时执行，他们都要去修改a的值，那么这个时候就只能动用锁机制来保证同一时间只能有一个命令操作。</p>
<p>虽然Redis中也有锁机制，但是它是一种乐观锁，不同于MySQL，我们在MySQL中认识的锁是悲观锁，那么什么是乐观锁什么是悲观锁呢？</p>
<ul>
<li>悲观锁：时刻认为别人会来抢占资源，禁止一切外来访问，直到释放锁，具有强烈的排他性质。</li>
<li>乐观锁：并不认为会有人来抢占资源，所以会直接对数据进行操作，在操作时再去验证是否有其他人抢占资源。</li>
</ul>
<p>Redis中可以使用watch来监视一个目标，如果执行事务之前被监视目标发生了修改，则取消本次事务：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">watch</span><span class="w">
</span></code></pre></div><p>我们可以开两个客户端进行测试。</p>
<p>取消监视可以使用：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">unwatch</span><span class="w">
</span></code></pre></div><p>至此，Redis的基础内容就讲解完毕了，在之后的SpringCloud阶段，我们还会去讲解集群相关的知识，包括主从复制、哨兵模式等。</p>
<hr>
<h2 id="使用java与redis交互">使用Java与Redis交互</h2>
<p>既然了解了如何通过命令窗口操作Redis数据库，那么我们如何使用Java来操作呢？</p>
<p>这里我们需要使用到Jedis框架，它能够实现Java与Redis数据库的交互，依赖：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;dependencies&gt;</span>
    <span class="nt">&lt;dependency&gt;</span>
        <span class="nt">&lt;groupId&gt;</span>redis.clients<span class="nt">&lt;/groupId&gt;</span>
        <span class="nt">&lt;artifactId&gt;</span>jedis<span class="nt">&lt;/artifactId&gt;</span>
        <span class="nt">&lt;version&gt;</span>4.0.0<span class="nt">&lt;/version&gt;</span>
    <span class="nt">&lt;/dependency&gt;</span>
<span class="nt">&lt;/dependencies&gt;</span>
</code></pre></div><h3 id="基本操作-1">基本操作</h3>
<p>我们来看看如何连接Redis数据库，非常简单，只需要创建一个对象即可：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="c1">//创建Jedis对象
</span><span class="c1"></span>    <span class="n">Jedis</span> <span class="n">jedis</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Jedis</span><span class="o">(</span><span class="s">&#34;localhost&#34;</span><span class="o">,</span> <span class="n">6379</span><span class="o">);</span>
  	
  	<span class="c1">//使用之后关闭连接
</span><span class="c1"></span>  	<span class="n">jedis</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div><p>通过Jedis对象，我们就可以直接调用命令的同名方法来执行Redis命令了，比如：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="c1">//直接使用try-with-resouse，省去close
</span><span class="c1"></span>    <span class="k">try</span><span class="o">(</span><span class="n">Jedis</span> <span class="n">jedis</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Jedis</span><span class="o">(</span><span class="s">&#34;192.168.10.3&#34;</span><span class="o">,</span> <span class="n">6379</span><span class="o">)){</span>
        <span class="n">jedis</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&#34;test&#34;</span><span class="o">,</span> <span class="s">&#34;lbwnb&#34;</span><span class="o">);</span>   <span class="c1">//等同于 set test lbwnb 命令
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">jedis</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&#34;test&#34;</span><span class="o">));</span>  <span class="c1">//等同于 get test 命令
</span><span class="c1"></span>    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>Hash类型的数据也是这样：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span><span class="o">(</span><span class="n">Jedis</span> <span class="n">jedis</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Jedis</span><span class="o">(</span><span class="s">&#34;192.168.10.3&#34;</span><span class="o">,</span> <span class="n">6379</span><span class="o">)){</span>
        <span class="n">jedis</span><span class="o">.</span><span class="na">hset</span><span class="o">(</span><span class="s">&#34;hhh&#34;</span><span class="o">,</span> <span class="s">&#34;name&#34;</span><span class="o">,</span> <span class="s">&#34;sxc&#34;</span><span class="o">);</span>   <span class="c1">//等同于 hset hhh name sxc
</span><span class="c1"></span>        <span class="n">jedis</span><span class="o">.</span><span class="na">hset</span><span class="o">(</span><span class="s">&#34;hhh&#34;</span><span class="o">,</span> <span class="s">&#34;sex&#34;</span><span class="o">,</span> <span class="s">&#34;19&#34;</span><span class="o">);</span>    <span class="c1">//等同于 hset hhh age 19
</span><span class="c1"></span>        <span class="n">jedis</span><span class="o">.</span><span class="na">hgetAll</span><span class="o">(</span><span class="s">&#34;hhh&#34;</span><span class="o">).</span><span class="na">forEach</span><span class="o">((</span><span class="n">k</span><span class="o">,</span> <span class="n">v</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">k</span><span class="o">+</span><span class="s">&#34;: &#34;</span><span class="o">+</span><span class="n">v</span><span class="o">));</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们接着来看看列表操作：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span><span class="o">(</span><span class="n">Jedis</span> <span class="n">jedis</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Jedis</span><span class="o">(</span><span class="s">&#34;192.168.10.3&#34;</span><span class="o">,</span> <span class="n">6379</span><span class="o">)){</span>
        <span class="n">jedis</span><span class="o">.</span><span class="na">lpush</span><span class="o">(</span><span class="s">&#34;mylist&#34;</span><span class="o">,</span> <span class="s">&#34;111&#34;</span><span class="o">,</span> <span class="s">&#34;222&#34;</span><span class="o">,</span> <span class="s">&#34;333&#34;</span><span class="o">);</span>  <span class="c1">//等同于 lpush mylist 111 222 333 命令
</span><span class="c1"></span>        <span class="n">jedis</span><span class="o">.</span><span class="na">lrange</span><span class="o">(</span><span class="s">&#34;mylist&#34;</span><span class="o">,</span> <span class="n">0</span><span class="o">,</span> <span class="o">-</span><span class="n">1</span><span class="o">)</span>
                <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span>    <span class="c1">//等同于 lrange mylist 0 -1
</span><span class="c1"></span>    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>实际上我们只需要按照对应的操作去调用同名方法即可，所有的类型封装Jedis已经帮助我们完成了。</p>
<h3 id="springboot整合redis">SpringBoot整合Redis</h3>
<p>我们接着来看如何在SpringBoot项目中整合Redis操作框架，只需要一个starter即可，但是它底层没有用Jedis，而是Lettuce：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;dependency&gt;</span>
    <span class="nt">&lt;groupId&gt;</span>org.springframework.boot<span class="nt">&lt;/groupId&gt;</span>
    <span class="nt">&lt;artifactId&gt;</span>spring-boot-starter-data-redis<span class="nt">&lt;/artifactId&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>
</code></pre></div><p>starter提供的默认配置会去连接本地的Redis服务器，并使用0号数据库，当然你也可以手动进行修改：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="nt">spring</span><span class="p">:</span><span class="w">
</span><span class="w">  </span><span class="nt">redis</span><span class="p">:</span><span class="w">
</span><span class="w">  	</span><span class="c">#Redis服务器地址</span><span class="w">
</span><span class="w">    </span><span class="nt">host</span><span class="p">:</span><span class="w"> </span><span class="m">192.168.10.3</span><span class="w">
</span><span class="w">    </span><span class="c">#端口</span><span class="w">
</span><span class="w">    </span><span class="nt">port</span><span class="p">:</span><span class="w"> </span><span class="m">6379</span><span class="w">
</span><span class="w">    </span><span class="c">#使用几号数据库</span><span class="w">
</span><span class="w">    </span><span class="nt">database</span><span class="p">:</span><span class="w"> </span><span class="m">0</span><span class="w">
</span></code></pre></div><p>starter已经给我们提供了两个默认的模板类：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Configuration</span><span class="o">(</span>
    <span class="n">proxyBeanMethods</span> <span class="o">=</span> <span class="kc">false</span>
<span class="o">)</span>
<span class="nd">@ConditionalOnClass</span><span class="o">({</span><span class="n">RedisOperations</span><span class="o">.</span><span class="na">class</span><span class="o">})</span>
<span class="nd">@EnableConfigurationProperties</span><span class="o">({</span><span class="n">RedisProperties</span><span class="o">.</span><span class="na">class</span><span class="o">})</span>
<span class="nd">@Import</span><span class="o">({</span><span class="n">LettuceConnectionConfiguration</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="n">JedisConnectionConfiguration</span><span class="o">.</span><span class="na">class</span><span class="o">})</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">RedisAutoConfiguration</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="nf">RedisAutoConfiguration</span><span class="o">()</span> <span class="o">{</span>
    <span class="o">}</span>

    <span class="nd">@Bean</span>
    <span class="nd">@ConditionalOnMissingBean</span><span class="o">(</span>
        <span class="n">name</span> <span class="o">=</span> <span class="o">{</span><span class="s">&#34;redisTemplate&#34;</span><span class="o">}</span>
    <span class="o">)</span>
    <span class="nd">@ConditionalOnSingleCandidate</span><span class="o">(</span><span class="n">RedisConnectionFactory</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
    <span class="kd">public</span> <span class="n">RedisTemplate</span><span class="o">&lt;</span><span class="n">Object</span><span class="o">,</span> <span class="n">Object</span><span class="o">&gt;</span> <span class="nf">redisTemplate</span><span class="o">(</span><span class="n">RedisConnectionFactory</span> <span class="n">redisConnectionFactory</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">RedisTemplate</span><span class="o">&lt;</span><span class="n">Object</span><span class="o">,</span> <span class="n">Object</span><span class="o">&gt;</span> <span class="n">template</span> <span class="o">=</span> <span class="k">new</span> <span class="n">RedisTemplate</span><span class="o">();</span>
        <span class="n">template</span><span class="o">.</span><span class="na">setConnectionFactory</span><span class="o">(</span><span class="n">redisConnectionFactory</span><span class="o">);</span>
        <span class="k">return</span> <span class="n">template</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="nd">@Bean</span>
    <span class="nd">@ConditionalOnMissingBean</span>
    <span class="nd">@ConditionalOnSingleCandidate</span><span class="o">(</span><span class="n">RedisConnectionFactory</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
    <span class="kd">public</span> <span class="n">StringRedisTemplate</span> <span class="nf">stringRedisTemplate</span><span class="o">(</span><span class="n">RedisConnectionFactory</span> <span class="n">redisConnectionFactory</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">return</span> <span class="k">new</span> <span class="n">StringRedisTemplate</span><span class="o">(</span><span class="n">redisConnectionFactory</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>那么如何去使用这两个模板类呢？我们可以直接注入<code>StringRedisTemplate</code>来使用模板：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@SpringBootTest</span>
<span class="kd">class</span> <span class="nc">SpringBootTestApplicationTests</span> <span class="o">{</span>

    <span class="nd">@Autowired</span>
    <span class="n">StringRedisTemplate</span> <span class="n">template</span><span class="o">;</span>

    <span class="nd">@Test</span>
    <span class="kt">void</span> <span class="nf">contextLoads</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">ValueOperations</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;</span> <span class="n">operations</span> <span class="o">=</span> <span class="n">template</span><span class="o">.</span><span class="na">opsForValue</span><span class="o">();</span>
        <span class="n">operations</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&#34;c&#34;</span><span class="o">,</span> <span class="s">&#34;xxxxx&#34;</span><span class="o">);</span>   <span class="c1">//设置值
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">operations</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&#34;c&#34;</span><span class="o">));</span>   <span class="c1">//获取值
</span><span class="c1"></span>      	
        <span class="n">template</span><span class="o">.</span><span class="na">delete</span><span class="o">(</span><span class="s">&#34;c&#34;</span><span class="o">);</span>    <span class="c1">//删除键
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">template</span><span class="o">.</span><span class="na">hasKey</span><span class="o">(</span><span class="s">&#34;c&#34;</span><span class="o">));</span>   <span class="c1">//判断是否包含键
</span><span class="c1"></span>    <span class="o">}</span>

<span class="o">}</span>
</code></pre></div><p>实际上所有的值的操作都被封装到了<code>ValueOperations</code>对象中，而普通的键操作直接通过模板对象就可以使用了，大致使用方式其实和Jedis一致。</p>
<p>我们接着来看看事务操作，由于Spring没有专门的Redis事务管理器，所以只能借用JDBC提供的，只不过无所谓，正常情况下反正我们也要用到这玩意：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;dependency&gt;</span>
    <span class="nt">&lt;groupId&gt;</span>org.springframework.boot<span class="nt">&lt;/groupId&gt;</span>
    <span class="nt">&lt;artifactId&gt;</span>spring-boot-starter-jdbc<span class="nt">&lt;/artifactId&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>
<span class="nt">&lt;dependency&gt;</span>
    <span class="nt">&lt;groupId&gt;</span>mysql<span class="nt">&lt;/groupId&gt;</span>
    <span class="nt">&lt;artifactId&gt;</span>mysql-connector-java<span class="nt">&lt;/artifactId&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Service</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">RedisService</span> <span class="o">{</span>

    <span class="nd">@Resource</span>
    <span class="n">StringRedisTemplate</span> <span class="n">template</span><span class="o">;</span>

    <span class="nd">@PostConstruct</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">init</span><span class="o">(){</span>
        <span class="n">template</span><span class="o">.</span><span class="na">setEnableTransactionSupport</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span>   <span class="c1">//需要开启事务
</span><span class="c1"></span>    <span class="o">}</span>

    <span class="nd">@Transactional</span>    <span class="c1">//需要添加此注解
</span><span class="c1"></span>    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test</span><span class="o">(){</span>
        <span class="n">template</span><span class="o">.</span><span class="na">multi</span><span class="o">();</span>
        <span class="n">template</span><span class="o">.</span><span class="na">opsForValue</span><span class="o">().</span><span class="na">set</span><span class="o">(</span><span class="s">&#34;d&#34;</span><span class="o">,</span> <span class="s">&#34;xxxxx&#34;</span><span class="o">);</span>
        <span class="n">template</span><span class="o">.</span><span class="na">exec</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们还可以为RedisTemplate对象配置一个Serializer来实现对象的JSON存储：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Test</span>
<span class="kt">void</span> <span class="nf">contextLoad2</span><span class="o">()</span> <span class="o">{</span>
    <span class="c1">//注意Student需要实现序列化接口才能存入Redis
</span><span class="c1"></span>    <span class="n">template</span><span class="o">.</span><span class="na">opsForValue</span><span class="o">().</span><span class="na">set</span><span class="o">(</span><span class="s">&#34;student&#34;</span><span class="o">,</span> <span class="k">new</span> <span class="n">Student</span><span class="o">());</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">template</span><span class="o">.</span><span class="na">opsForValue</span><span class="o">().</span><span class="na">get</span><span class="o">(</span><span class="s">&#34;student&#34;</span><span class="o">));</span>
<span class="o">}</span>
</code></pre></div><hr>
<h2 id="使用redis做缓存">使用Redis做缓存</h2>
<p>我们可以轻松地使用Redis来实现一些框架的缓存和其他存储。</p>
<h3 id="mybatis二级缓存">Mybatis二级缓存</h3>
<p>还记得我们在学习Mybatis讲解的缓存机制吗，我们当时介绍了二级缓存，它是Mapper级别的缓存，能够作用与所有会话。但是当时我们提出了一个问题，由于Mybatis的默认二级缓存只能是单机的，如果存在多台服务器访问同一个数据库，实际上二级缓存只会在各自的服务器上生效，但是我们希望的是多台服务器都能使用同一个二级缓存，这样就不会造成过多的资源浪费。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/img_convert/5afd7713f9a97615dc3a0b1d3bc7db27.png"
        data-srcset="https://img-blog.csdnimg.cn/img_convert/5afd7713f9a97615dc3a0b1d3bc7db27.png, https://img-blog.csdnimg.cn/img_convert/5afd7713f9a97615dc3a0b1d3bc7db27.png 1.5x, https://img-blog.csdnimg.cn/img_convert/5afd7713f9a97615dc3a0b1d3bc7db27.png 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/img_convert/5afd7713f9a97615dc3a0b1d3bc7db27.png"
        title="img" /></p>
<p>我们可以将Redis作为Mybatis的二级缓存，这样就能实现多台服务器使用同一个二级缓存，因为它们只需要连接同一个Redis服务器即可，所有的缓存数据全部存储在Redis服务器上。我们需要手动实现Mybatis提供的Cache接口，这里我们简单编写一下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">//实现Mybatis的Cache接口
</span><span class="c1"></span><span class="kd">public</span> <span class="kd">class</span> <span class="nc">RedisMybatisCache</span> <span class="kd">implements</span> <span class="n">Cache</span> <span class="o">{</span>

    <span class="kd">private</span> <span class="kd">final</span> <span class="n">String</span> <span class="n">id</span><span class="o">;</span>
    <span class="kd">private</span> <span class="kd">static</span> <span class="n">RedisTemplate</span><span class="o">&lt;</span><span class="n">Object</span><span class="o">,</span> <span class="n">Object</span><span class="o">&gt;</span> <span class="n">template</span><span class="o">;</span>

   	<span class="c1">//注意构造方法必须带一个String类型的参数接收id
</span><span class="c1"></span>    <span class="kd">public</span> <span class="nf">RedisMybatisCache</span><span class="o">(</span><span class="n">String</span> <span class="n">id</span><span class="o">){</span>
        <span class="k">this</span><span class="o">.</span><span class="na">id</span> <span class="o">=</span> <span class="n">id</span><span class="o">;</span>
    <span class="o">}</span>

  	<span class="c1">//初始化时通过配置类将RedisTemplate给过来
</span><span class="c1"></span>    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">setTemplate</span><span class="o">(</span><span class="n">RedisTemplate</span><span class="o">&lt;</span><span class="n">Object</span><span class="o">,</span> <span class="n">Object</span><span class="o">&gt;</span> <span class="n">template</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">RedisMybatisCache</span><span class="o">.</span><span class="na">template</span> <span class="o">=</span> <span class="n">template</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">String</span> <span class="nf">getId</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">id</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">putObject</span><span class="o">(</span><span class="n">Object</span> <span class="n">o</span><span class="o">,</span> <span class="n">Object</span> <span class="n">o1</span><span class="o">)</span> <span class="o">{</span>
      	<span class="c1">//这里直接向Redis数据库中丢数据即可，o就是Key，o1就是Value，60秒为过期时间
</span><span class="c1"></span>        <span class="n">template</span><span class="o">.</span><span class="na">opsForValue</span><span class="o">().</span><span class="na">set</span><span class="o">(</span><span class="n">o</span><span class="o">,</span> <span class="n">o1</span><span class="o">,</span> <span class="n">60</span><span class="o">,</span> <span class="n">TimeUnit</span><span class="o">.</span><span class="na">SECONDS</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">Object</span> <span class="nf">getObject</span><span class="o">(</span><span class="n">Object</span> <span class="n">o</span><span class="o">)</span> <span class="o">{</span>
      	<span class="c1">//这里根据Key直接从Redis数据库中获取值即可
</span><span class="c1"></span>        <span class="k">return</span> <span class="n">template</span><span class="o">.</span><span class="na">opsForValue</span><span class="o">().</span><span class="na">get</span><span class="o">(</span><span class="n">o</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">Object</span> <span class="nf">removeObject</span><span class="o">(</span><span class="n">Object</span> <span class="n">o</span><span class="o">)</span> <span class="o">{</span>
      	<span class="c1">//根据Key删除
</span><span class="c1"></span>        <span class="k">return</span> <span class="n">template</span><span class="o">.</span><span class="na">delete</span><span class="o">(</span><span class="n">o</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">clear</span><span class="o">()</span> <span class="o">{</span>
      	<span class="c1">//由于template中没封装清除操作，只能通过connection来执行
</span><span class="c1"></span>				<span class="n">template</span><span class="o">.</span><span class="na">execute</span><span class="o">((</span><span class="n">RedisCallback</span><span class="o">&lt;</span><span class="n">Void</span><span class="o">&gt;)</span> <span class="n">connection</span> <span class="o">-&gt;</span> <span class="o">{</span>
          	<span class="c1">//通过connection对象执行清空操作
</span><span class="c1"></span>            <span class="n">connection</span><span class="o">.</span><span class="na">flushDb</span><span class="o">();</span>
            <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
        <span class="o">});</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">int</span> <span class="nf">getSize</span><span class="o">()</span> <span class="o">{</span>
      	<span class="c1">//这里也是使用connection对象来获取当前的Key数量
</span><span class="c1"></span>        <span class="k">return</span> <span class="n">template</span><span class="o">.</span><span class="na">execute</span><span class="o">(</span><span class="n">RedisServerCommands</span><span class="o">::</span><span class="n">dbSize</span><span class="o">).</span><span class="na">intValue</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>缓存类编写完成后，我们接着来编写配置类：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Configuration</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">MainConfiguration</span> <span class="o">{</span>
    <span class="nd">@Resource</span>
    <span class="n">RedisTemplate</span><span class="o">&lt;</span><span class="n">Object</span><span class="o">,</span> <span class="n">Object</span><span class="o">&gt;</span> <span class="n">template</span><span class="o">;</span>

    <span class="nd">@PostConstruct</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">init</span><span class="o">(){</span>
      	<span class="c1">//把RedisTemplate给到RedisMybatisCache
</span><span class="c1"></span>        <span class="n">RedisMybatisCache</span><span class="o">.</span><span class="na">setTemplate</span><span class="o">(</span><span class="n">template</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>最后我们在Mapper上启用此缓存即可：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">//只需要修改缓存实现类implementation为我们的RedisMybatisCache即可
</span><span class="c1"></span><span class="nd">@CacheNamespace</span><span class="o">(</span><span class="n">implementation</span> <span class="o">=</span> <span class="n">RedisMybatisCache</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
<span class="nd">@Mapper</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">MainMapper</span> <span class="o">{</span>

    <span class="nd">@Select</span><span class="o">(</span><span class="s">&#34;select name from student where sid = 1&#34;</span><span class="o">)</span>
    <span class="n">String</span> <span class="nf">getSid</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div><p>最后我们提供一个测试用例来查看当前的二级缓存是否生效：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@SpringBootTest</span>
<span class="kd">class</span> <span class="nc">SpringBootTestApplicationTests</span> <span class="o">{</span>


    <span class="nd">@Resource</span>
    <span class="n">MainMapper</span> <span class="n">mapper</span><span class="o">;</span>

    <span class="nd">@Test</span>
    <span class="kt">void</span> <span class="nf">contextLoads</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">mapper</span><span class="o">.</span><span class="na">getSid</span><span class="o">());</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">mapper</span><span class="o">.</span><span class="na">getSid</span><span class="o">());</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">mapper</span><span class="o">.</span><span class="na">getSid</span><span class="o">());</span>
    <span class="o">}</span>

<span class="o">}</span>
</code></pre></div><p>手动使用客户端查看Redis数据库，可以看到已经有一条Mybatis生成的缓存数据了。</p>
<h3 id="token持久化存储">Token持久化存储</h3>
<p>我们之前使用SpringSecurity时，remember-me的Token是支持持久化存储的，而我们当时是存储在数据库中，那么Token信息能否存储在缓存中呢，当然也是可以的，我们可以手动实现一个：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">//实现PersistentTokenRepository接口
</span><span class="c1"></span><span class="nd">@Component</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">RedisTokenRepository</span> <span class="kd">implements</span> <span class="n">PersistentTokenRepository</span> <span class="o">{</span>
  	<span class="c1">//Key名称前缀，用于区分
</span><span class="c1"></span>    <span class="kd">private</span> <span class="kd">final</span> <span class="kd">static</span> <span class="n">String</span> <span class="n">REMEMBER_ME_KEY</span> <span class="o">=</span> <span class="s">&#34;spring:security:rememberMe:&#34;</span><span class="o">;</span>
    <span class="nd">@Resource</span>
    <span class="n">RedisTemplate</span><span class="o">&lt;</span><span class="n">Object</span><span class="o">,</span> <span class="n">Object</span><span class="o">&gt;</span> <span class="n">template</span><span class="o">;</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">createNewToken</span><span class="o">(</span><span class="n">PersistentRememberMeToken</span> <span class="n">token</span><span class="o">)</span> <span class="o">{</span>
      	<span class="c1">//这里要放两个，一个存seriesId-&gt;Token，一个存username-&gt;seriesId，因为删除时是通过username删除
</span><span class="c1"></span>        <span class="n">template</span><span class="o">.</span><span class="na">opsForValue</span><span class="o">().</span><span class="na">set</span><span class="o">(</span><span class="n">REMEMBER_ME_KEY</span><span class="o">+</span><span class="s">&#34;username:&#34;</span><span class="o">+</span><span class="n">token</span><span class="o">.</span><span class="na">getUsername</span><span class="o">(),</span> <span class="n">token</span><span class="o">.</span><span class="na">getSeries</span><span class="o">());</span>
        <span class="n">template</span><span class="o">.</span><span class="na">expire</span><span class="o">(</span><span class="n">REMEMBER_ME_KEY</span><span class="o">+</span><span class="s">&#34;username:&#34;</span><span class="o">+</span><span class="n">token</span><span class="o">.</span><span class="na">getUsername</span><span class="o">(),</span> <span class="n">1</span><span class="o">,</span> <span class="n">TimeUnit</span><span class="o">.</span><span class="na">DAYS</span><span class="o">);</span>
        <span class="k">this</span><span class="o">.</span><span class="na">setToken</span><span class="o">(</span><span class="n">token</span><span class="o">);</span>
    <span class="o">}</span>

  	<span class="c1">//先获取，然后修改创建一个新的，再放入
</span><span class="c1"></span>    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">updateToken</span><span class="o">(</span><span class="n">String</span> <span class="n">series</span><span class="o">,</span> <span class="n">String</span> <span class="n">tokenValue</span><span class="o">,</span> <span class="n">Date</span> <span class="n">lastUsed</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">PersistentRememberMeToken</span> <span class="n">token</span> <span class="o">=</span> <span class="k">this</span><span class="o">.</span><span class="na">getToken</span><span class="o">(</span><span class="n">series</span><span class="o">);</span>
        <span class="k">if</span><span class="o">(</span><span class="n">token</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span>
           <span class="k">this</span><span class="o">.</span><span class="na">setToken</span><span class="o">(</span><span class="k">new</span> <span class="n">PersistentRememberMeToken</span><span class="o">(</span><span class="n">token</span><span class="o">.</span><span class="na">getUsername</span><span class="o">(),</span> <span class="n">series</span><span class="o">,</span> <span class="n">tokenValue</span><span class="o">,</span> <span class="n">lastUsed</span><span class="o">));</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">PersistentRememberMeToken</span> <span class="nf">getTokenForSeries</span><span class="o">(</span><span class="n">String</span> <span class="n">seriesId</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">return</span> <span class="k">this</span><span class="o">.</span><span class="na">getToken</span><span class="o">(</span><span class="n">seriesId</span><span class="o">);</span>
    <span class="o">}</span>

  	<span class="c1">//通过username找seriesId直接删除这两个
</span><span class="c1"></span>    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">removeUserTokens</span><span class="o">(</span><span class="n">String</span> <span class="n">username</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">String</span> <span class="n">series</span> <span class="o">=</span> <span class="o">(</span><span class="n">String</span><span class="o">)</span> <span class="n">template</span><span class="o">.</span><span class="na">opsForValue</span><span class="o">().</span><span class="na">get</span><span class="o">(</span><span class="n">REMEMBER_ME_KEY</span><span class="o">+</span><span class="s">&#34;username:&#34;</span><span class="o">+</span><span class="n">username</span><span class="o">);</span>
        <span class="n">template</span><span class="o">.</span><span class="na">delete</span><span class="o">(</span><span class="n">REMEMBER_ME_KEY</span><span class="o">+</span><span class="n">series</span><span class="o">);</span>
        <span class="n">template</span><span class="o">.</span><span class="na">delete</span><span class="o">(</span><span class="n">REMEMBER_ME_KEY</span><span class="o">+</span><span class="s">&#34;username:&#34;</span><span class="o">+</span><span class="n">username</span><span class="o">);</span>
    <span class="o">}</span>

  
  	<span class="c1">//由于PersistentRememberMeToken没实现序列化接口，这里只能用Hash来存储了，所以单独编写一个set和get操作
</span><span class="c1"></span>    <span class="kd">private</span> <span class="n">PersistentRememberMeToken</span> <span class="nf">getToken</span><span class="o">(</span><span class="n">String</span> <span class="n">series</span><span class="o">){</span>
        <span class="n">Map</span><span class="o">&lt;</span><span class="n">Object</span><span class="o">,</span> <span class="n">Object</span><span class="o">&gt;</span> <span class="n">map</span> <span class="o">=</span> <span class="n">template</span><span class="o">.</span><span class="na">opsForHash</span><span class="o">().</span><span class="na">entries</span><span class="o">(</span><span class="n">REMEMBER_ME_KEY</span><span class="o">+</span><span class="n">series</span><span class="o">);</span>
        <span class="k">if</span><span class="o">(</span><span class="n">map</span><span class="o">.</span><span class="na">isEmpty</span><span class="o">())</span> <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
        <span class="k">return</span> <span class="k">new</span> <span class="n">PersistentRememberMeToken</span><span class="o">(</span>
                <span class="o">(</span><span class="n">String</span><span class="o">)</span> <span class="n">map</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&#34;username&#34;</span><span class="o">),</span>
                <span class="o">(</span><span class="n">String</span><span class="o">)</span> <span class="n">map</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&#34;series&#34;</span><span class="o">),</span>
                <span class="o">(</span><span class="n">String</span><span class="o">)</span> <span class="n">map</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&#34;tokenValue&#34;</span><span class="o">),</span>
                <span class="k">new</span> <span class="n">Date</span><span class="o">(</span><span class="n">Long</span><span class="o">.</span><span class="na">parseLong</span><span class="o">((</span><span class="n">String</span><span class="o">)</span> <span class="n">map</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&#34;date&#34;</span><span class="o">))));</span>
    <span class="o">}</span>

    <span class="kd">private</span> <span class="kt">void</span> <span class="nf">setToken</span><span class="o">(</span><span class="n">PersistentRememberMeToken</span> <span class="n">token</span><span class="o">){</span>
        <span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;</span> <span class="n">map</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;&gt;();</span>
        <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&#34;username&#34;</span><span class="o">,</span> <span class="n">token</span><span class="o">.</span><span class="na">getUsername</span><span class="o">());</span>
        <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&#34;series&#34;</span><span class="o">,</span> <span class="n">token</span><span class="o">.</span><span class="na">getSeries</span><span class="o">());</span>
        <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&#34;tokenValue&#34;</span><span class="o">,</span> <span class="n">token</span><span class="o">.</span><span class="na">getTokenValue</span><span class="o">());</span>
        <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&#34;date&#34;</span><span class="o">,</span> <span class="s">&#34;&#34;</span><span class="o">+</span><span class="n">token</span><span class="o">.</span><span class="na">getDate</span><span class="o">().</span><span class="na">getTime</span><span class="o">());</span>
        <span class="n">template</span><span class="o">.</span><span class="na">opsForHash</span><span class="o">().</span><span class="na">putAll</span><span class="o">(</span><span class="n">REMEMBER_ME_KEY</span><span class="o">+</span><span class="n">token</span><span class="o">.</span><span class="na">getSeries</span><span class="o">(),</span> <span class="n">map</span><span class="o">);</span>
        <span class="n">template</span><span class="o">.</span><span class="na">expire</span><span class="o">(</span><span class="n">REMEMBER_ME_KEY</span><span class="o">+</span><span class="n">token</span><span class="o">.</span><span class="na">getSeries</span><span class="o">(),</span> <span class="n">1</span><span class="o">,</span> <span class="n">TimeUnit</span><span class="o">.</span><span class="na">DAYS</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>接着把验证Service实现了：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Service</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">AuthService</span> <span class="kd">implements</span> <span class="n">UserDetailsService</span> <span class="o">{</span>

    <span class="nd">@Resource</span>
    <span class="n">UserMapper</span> <span class="n">mapper</span><span class="o">;</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">UserDetails</span> <span class="nf">loadUserByUsername</span><span class="o">(</span><span class="n">String</span> <span class="n">username</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">UsernameNotFoundException</span> <span class="o">{</span>
        <span class="n">Account</span> <span class="n">account</span> <span class="o">=</span> <span class="n">mapper</span><span class="o">.</span><span class="na">getAccountByUsername</span><span class="o">(</span><span class="n">username</span><span class="o">);</span>
        <span class="k">if</span><span class="o">(</span><span class="n">account</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="k">throw</span> <span class="k">new</span> <span class="n">UsernameNotFoundException</span><span class="o">(</span><span class="s">&#34;&#34;</span><span class="o">);</span>
        <span class="k">return</span> <span class="n">User</span>
                <span class="o">.</span><span class="na">withUsername</span><span class="o">(</span><span class="n">username</span><span class="o">)</span>
                <span class="o">.</span><span class="na">password</span><span class="o">(</span><span class="n">account</span><span class="o">.</span><span class="na">getPassword</span><span class="o">())</span>
                <span class="o">.</span><span class="na">roles</span><span class="o">(</span><span class="n">account</span><span class="o">.</span><span class="na">getRole</span><span class="o">())</span>
                <span class="o">.</span><span class="na">build</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>Mapper也安排上：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Data</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Account</span> <span class="kd">implements</span> <span class="n">Serializable</span> <span class="o">{</span>
    <span class="kt">int</span> <span class="n">id</span><span class="o">;</span>
    <span class="n">String</span> <span class="n">username</span><span class="o">;</span>
    <span class="n">String</span> <span class="n">password</span><span class="o">;</span>
    <span class="n">String</span> <span class="n">role</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@CacheNamespace</span><span class="o">(</span><span class="n">implementation</span> <span class="o">=</span> <span class="n">MybatisRedisCache</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
<span class="nd">@Mapper</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">UserMapper</span> <span class="o">{</span>

    <span class="nd">@Select</span><span class="o">(</span><span class="s">&#34;select * from users where username = #{username}&#34;</span><span class="o">)</span>
    <span class="n">Account</span> <span class="nf">getAccountByUsername</span><span class="o">(</span><span class="n">String</span> <span class="n">username</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>最后配置文件配一波：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Override</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">configure</span><span class="o">(</span><span class="n">HttpSecurity</span> <span class="n">http</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Exception</span> <span class="o">{</span>
    <span class="n">http</span>
            <span class="o">.</span><span class="na">authorizeRequests</span><span class="o">()</span>
            <span class="o">.</span><span class="na">anyRequest</span><span class="o">().</span><span class="na">authenticated</span><span class="o">()</span>
            <span class="o">.</span><span class="na">and</span><span class="o">()</span>
            <span class="o">.</span><span class="na">formLogin</span><span class="o">()</span>
            <span class="o">.</span><span class="na">and</span><span class="o">()</span>
            <span class="o">.</span><span class="na">rememberMe</span><span class="o">()</span>
            <span class="o">.</span><span class="na">tokenRepository</span><span class="o">(</span><span class="n">repository</span><span class="o">);</span>
<span class="o">}</span>

<span class="nd">@Override</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">configure</span><span class="o">(</span><span class="n">AuthenticationManagerBuilder</span> <span class="n">auth</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Exception</span> <span class="o">{</span>
    <span class="n">auth</span>
            <span class="o">.</span><span class="na">userDetailsService</span><span class="o">(</span><span class="n">service</span><span class="o">)</span>
            <span class="o">.</span><span class="na">passwordEncoder</span><span class="o">(</span><span class="k">new</span> <span class="n">BCryptPasswordEncoder</span><span class="o">());</span>
<span class="o">}</span>
</code></pre></div><p>OK，启动服务器验证一下吧。</p>
<hr>
<h2 id="三大缓存问题">三大缓存问题</h2>
<p>**注意：**这部分内容作为选学内容。</p>
<p>虽然我们可以利用缓存来大幅度提升我们程序的数据获取效率，但是使用缓存也存在着一些潜在的问题。</p>
<h3 id="缓存穿透">缓存穿透</h3>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1004.png?x-oss-process=style/shuiyin"
        data-srcset="https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1004.png?x-oss-process=style/shuiyin, https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1004.png?x-oss-process=style/shuiyin 1.5x, https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1004.png?x-oss-process=style/shuiyin 2x"
        data-sizes="auto"
        alt="https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1004.png?x-oss-process=style/shuiyin"
        title="img" /></p>
<p>当我们去查询一个一定不存在的数据，比如Mybatis在缓存是未命中的情况下需要从数据库查询，查不到数据则不写入缓存，这将导致这个不存在的数据每次请求都要到数据库去查询，造成缓存穿透。</p>
<p>这显然是很浪费资源的，我们希望的是，如果这个数据不存在，为什么缓存这一层不直接返回空呢，这时就不必再去查数据库了，但是也有一个问题，缓存不去查数据库怎么知道数据库里面到底有没有这个数据呢？</p>
<p>这时我们就可以使用布隆过滤器来进行判断。什么是布隆过滤器？（当然不是打辅助的那个布隆，只不过也挺像，辅助布隆也是挡子弹的）</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage.bubuko.com%2Finfo%2F201903%2F20190321142642446276.png&amp;refer=http%3A%2F%2Fimage.bubuko.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644902390&amp;t=4f0440b0357965ead1fa34fb27513927"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage.bubuko.com%2Finfo%2F201903%2F20190321142642446276.png&amp;refer=http%3A%2F%2Fimage.bubuko.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644902390&amp;t=4f0440b0357965ead1fa34fb27513927, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage.bubuko.com%2Finfo%2F201903%2F20190321142642446276.png&amp;refer=http%3A%2F%2Fimage.bubuko.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644902390&amp;t=4f0440b0357965ead1fa34fb27513927 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage.bubuko.com%2Finfo%2F201903%2F20190321142642446276.png&amp;refer=http%3A%2F%2Fimage.bubuko.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644902390&amp;t=4f0440b0357965ead1fa34fb27513927 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage.bubuko.com%2Finfo%2F201903%2F20190321142642446276.png&amp;refer=http%3A%2F%2Fimage.bubuko.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1644902390&amp;t=4f0440b0357965ead1fa34fb27513927"
        title="点击查看图片来源" /></p>
<p>使用布隆过滤器，能够告诉你某样东西一定不存在或是某样东西可能存在。</p>
<p>布隆过滤器本质是一个存放二进制位的bit数组，如果我们要添加一个值到布隆过滤器中，我们需要使用N个不同的哈希函数来生成N个哈希值，并对每个生成的哈希值指向的bit位置1，如上图所示，一共添加了三个值abc。</p>
<p>接着我们给一个d，那么这时就可以进行判断，如果说d计算的N个哈希值的位置上都是1，那么就说明d可能存在；这时候又来了个e，计算后我们发现有一个位置上的值是0，这时就可以直接断定e一定不存在。</p>
<h3 id="缓存击穿">缓存击穿</h3>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1005.png?x-oss-process=style/shuiyin"
        data-srcset="https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1005.png?x-oss-process=style/shuiyin, https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1005.png?x-oss-process=style/shuiyin 1.5x, https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1005.png?x-oss-process=style/shuiyin 2x"
        data-sizes="auto"
        alt="https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1005.png?x-oss-process=style/shuiyin"
        title="img" /></p>
<p>某个 Key 属于热点数据，访问非常频繁，同一时间很多人都在访问，在这个Key失效的瞬间，大量的请求到来，这时发现缓存中没有数据，就全都直接请求数据库，相当于击穿了缓存屏障，直接攻击整个系统核心。</p>
<p>这种情况下，最好的解决办法就是不让Key那么快过期，如果一个Key处于高频访问，那么可以适当地延长过期时间。</p>
<h3 id="缓存雪崩">缓存雪崩</h3>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1006.png?x-oss-process=style/shuiyin"
        data-srcset="https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1006.png?x-oss-process=style/shuiyin, https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1006.png?x-oss-process=style/shuiyin 1.5x, https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1006.png?x-oss-process=style/shuiyin 2x"
        data-sizes="auto"
        alt="https://mydlq-club.oss-cn-beijing.aliyuncs.com/images/springboot-cache-redis-1006.png?x-oss-process=style/shuiyin"
        title="img" /></p>
<p>当你的Redis服务器炸了或是大量的Key在同一时间过期，这时相当于缓存直接GG了，那么如果这时又有很多的请求来访问不同的数据，同一时间内缓存服务器就得向数据库大量发起请求来重新建立缓存，很容易把数据库也搞GG。</p>
<p>解决这种问题最好的办法就是设置高可用，也就是搭建Redis集群，当然也可以采取一些服务熔断降级机制，这些内容我们会在SpringCloud阶段再进行探讨。</p>
</div><div class="post-footer" id="post-footer">
    <div class="post-info"><div class="post-info-tag"><span><a href="/tags/redis%E7%9A%84%E4%BB%8B%E7%BB%8D%E4%B8%8E%E4%BD%BF%E7%94%A8/">redis的介绍与使用</a>
                </span></div><div class="post-info-line"><div class="post-info-mod">
                <span>更新于 2022-06-11</span>
            </div><div class="post-info-mod"></div>
        </div><div class="post-info-share">
            <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://acking-you.github.io/posts/redis%E7%9A%84%E4%BB%8B%E7%BB%8D%E4%B8%8E%E4%BD%BF%E7%94%A8/" data-title="redis的介绍与使用" data-hashtags="redis的介绍与使用"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://acking-you.github.io/posts/redis%E7%9A%84%E4%BB%8B%E7%BB%8D%E4%B8%8E%E4%BD%BF%E7%94%A8/" data-hashtag="redis的介绍与使用"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://acking-you.github.io/posts/redis%E7%9A%84%E4%BB%8B%E7%BB%8D%E4%B8%8E%E4%BD%BF%E7%94%A8/" data-title="redis的介绍与使用" data-web><i class="fab fa-whatsapp fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://acking-you.github.io/posts/redis%E7%9A%84%E4%BB%8B%E7%BB%8D%E4%B8%8E%E4%BD%BF%E7%94%A8/" data-title="redis的介绍与使用"><i class="fab fa-line fa-fw"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://acking-you.github.io/posts/redis%E7%9A%84%E4%BB%8B%E7%BB%8D%E4%B8%8E%E4%BD%BF%E7%94%A8/" data-title="redis的介绍与使用" data-image="https://img-blog.csdnimg.cn/img_convert/e706274b97f65b3aac9471d1da024918.png#pic_center"><i class="fab fa-weibo fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Myspace" data-sharer="myspace" data-url="https://acking-you.github.io/posts/redis%E7%9A%84%E4%BB%8B%E7%BB%8D%E4%B8%8E%E4%BD%BF%E7%94%A8/" data-title="redis的介绍与使用" data-description="redis的介绍与使用"><i data-svg-src="/lib/simple-icons/icons/myspace.min.svg"></i></a><a href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://acking-you.github.io/posts/redis%E7%9A%84%E4%BB%8B%E7%BB%8D%E4%B8%8E%E4%BD%BF%E7%94%A8/" data-title="redis的介绍与使用" data-description="redis的介绍与使用"><i class="fab fa-blogger fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Evernote" data-sharer="evernote" data-url="https://acking-you.github.io/posts/redis%E7%9A%84%E4%BB%8B%E7%BB%8D%E4%B8%8E%E4%BD%BF%E7%94%A8/" data-title="redis的介绍与使用"><i class="fab fa-evernote fa-fw"></i></a></span>
        </div></div><div class="post-nav"><a href="/posts/java%E8%AF%BE%E8%AE%BEswing%E7%94%A8%E5%88%86%E5%B1%82%E6%80%9D%E6%83%B3%E6%B5%85%E5%86%99%E4%B8%AA%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F%E8%AF%BE%E8%AE%BE/" class="prev" rel="prev" title="[Java课设]Swing用分层思想浅写个管理系统课设"><i class="fas fa-angle-left fa-fw"></i>Previous Post</a>
            <a href="/posts/%E9%9D%A2%E8%AF%95%E5%85%AB%E8%82%A1%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C1/" class="next" rel="next" title="面试八股——计算机网络1">Next Post<i class="fas fa-angle-right fa-fw"></i></a></div></div>
</div></article></div>
            </main>
            <footer class="footer"><div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.86.0">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/khusika/FeelIt" target="_blank" rel="noopener noreffer" title="FeelIt 1.0.1"><i class="fas fa-hand-holding-heart fa-fw"></i> FeelIt</a>
        </div><div class="footer-line" itemscope itemtype="http://schema.org/CreativeWork"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2023</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/"></a></span></div>
</div>
</footer>
        </div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-chevron-up fa-fw"></i>
            </a></div><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><link rel="stylesheet" href="/lib/katex/katex.min.css"><link rel="stylesheet" href="/lib/katex/copy-tex.min.css"><script src="/lib/autocomplete/autocomplete.min.js"></script><script src="/lib/lunr/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="/lib/lazysizes/lazysizes.min.js"></script><script src="/lib/clipboard/clipboard.min.js"></script><script src="/lib/sharer/sharer.min.js"></script><script src="/lib/katex/katex.min.js"></script><script src="/lib/katex/auto-render.min.js"></script><script src="/lib/katex/copy-tex.min.js"></script><script src="/lib/katex/mhchem.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":200},"comment":{},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":100,"noResultsFound":"没有找到结果","snippetLength":50,"type":"lunr"}};</script><script src="/js/theme.min.js"></script></body></html>
